import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoggedIn: false
  }),
  
  getters: {
    // 获取用户类型
    userType: (state) => state.userInfo?.userType,
    
    // 获取用户ID
    userId: (state) => state.userInfo?.userId,
    
    // 获取用户名
    username: (state) => state.userInfo?.username,
    
    // 判断是否是患者
    isPatient: (state) => state.userInfo?.userType === 1,
    
    // 判断是否是护工
    isCaregiver: (state) => state.userInfo?.userType === 2,
    
    // 判断是否是管理员
    isAdmin: (state) => state.userInfo?.userType === 3
  },
  
  actions: {
    // 登录成功后保存用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = true
      
      // 同时保存到 localStorage 作为备份
      localStorage.setItem('user', JSON.stringify(userInfo))
    },
    
    // 从 localStorage 恢复用户信息
    loadUserInfo() {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        try {
          this.userInfo = JSON.parse(userStr)
          this.isLoggedIn = true
          return true
        } catch (e) {
          console.error('Failed to parse user info from localStorage', e)
        }
      }
      return false
    },
    
    // 退出登录
    logout() {
      this.userInfo = null
      this.isLoggedIn = false
      localStorage.removeItem('user')
    }
  }
}) 